﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.Serialization.Json;

using Xunit;

namespace CrudServices.Tests
{
    public sealed class DevTests
    {
        [Fact]
        public void Test()
        {
            SearchCriteria criteria = SearchCriteriaBuilder.From<Customer>()
                .Where(c => c.Age == 18)
                .Where(c => c.Mobile != null)
                .OrderBy(c => c.FirstName, c => c.LastName)
                .Limit(10)
                .SelectAll();
            Debug.WriteLine(criteria);
        }

        [Fact]
        public void SerializeTest()
        {
            int minAge = DateTime.Now.Second % 2 == 0 ? 18 : 21;
            SearchCriteria criteria = SearchCriteriaBuilder.From<Customer>()
                .Where(c => c.Age == MinAge)
                .Where(c => c.Mobile != null)
                .OrderBy(c => c.FirstName, c => c.LastName)
                .Limit(10)
                .SelectAll();
            var serializer = new DataContractJsonSerializer(typeof(SearchCriteria));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, criteria);
                stream.Seek(0, SeekOrigin.Begin);
                Debug.WriteLine(new StreamReader(stream).ReadToEnd());
            }
        }

        [Fact]
        public void ExpressionTest()
        {
            ParameterExpression c = Expression.Variable(typeof(Customer), "c");
            MemberAssignment memberAssignment = Expression.Bind(typeof(Customer).GetProperty("FirstName"), Expression.Property(c, "FirstName"));
            MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(Customer)), memberAssignment);
            LambdaExpression lambda = Expression.Lambda(init, c);
            Expression<Func<Customer, Customer>> selector = customer => new Customer { FirstName = customer.FirstName, LastName = customer.LastName };
            Debug.WriteLine(selector);
        }

        private static readonly int MinAge = 32;
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string Mobile { get; set; }
    }
}